#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PyQt桌面应用启动脚本
自动检查并安装依赖，然后启动PyQt应用
"""

import os
import sys
import subprocess
import importlib.util

def check_dependencies():
    """检查并安装必要的依赖包"""
    required_packages = [
        'PyQt5',
        'requests', 
        'python-docx',
        'PyYAML'
    ]
    
    # Windows系统需要检查pywin32
    if sys.platform == "win32":
        required_packages.append('pywin32')
    
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == 'PyQt5':
                import PyQt5
            elif package == 'requests':
                import requests
            elif package == 'python-docx':
                import docx
            elif package == 'PyYAML':
                import yaml
            elif package == 'pywin32':
                import win32com
            print(f"✓ {package} 已安装")
        except ImportError:
            missing_packages.append(package)
            print(f"✗ {package} 未安装")
    
    return missing_packages

def install_packages(packages):
    """安装缺失的包"""
    if not packages:
        print("所有依赖包已安装完成")
        return True
    
    print(f"\n开始安装缺失的包: {', '.join(packages)}")
    
    try:
        # 使用pip安装所有缺失的包
        subprocess.check_call([sys.executable, "-m", "pip", "install"] + packages)
        print("✓ 依赖包安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖包安装失败: {e}")
        return False

def check_extract_directory():
    """检查extract目录结构"""
    required_files = ['pyqt_app.py', 'doc_trans.py', 'config.yaml']
    
    for file in required_files:
        if not os.path.exists(file):
            print(f"✗ 缺少必要文件: {file}")
            return False
        else:
            print(f"✓ {file} 存在")
    
    return True

def main():
    """主函数"""
    print("=" * 50)
    print("英文文档翻译工具 - PyQt桌面版启动器")
    print("=" * 50)
    
    # 检查当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print(f"当前目录: {current_dir}")
    
    # 检查extract目录结构
    print("\n1. 检查目录结构...")
    if not check_extract_directory():
        print("错误: 必要的文件缺失，请确保在extract目录下运行此脚本")
        input("按回车键退出...")
        return
    
    # 检查依赖包
    print("\n2. 检查依赖包...")
    missing_packages = check_dependencies()
    
    # 安装缺失的包
    if missing_packages:
        print("\n3. 安装缺失的依赖包...")
        if not install_packages(missing_packages):
            print("错误: 依赖包安装失败，请手动安装")
            input("按回车键退出...")
            return
    else:
        print("\n3. 所有依赖包已安装")
    
    # 启动PyQt应用
    print("\n4. 启动PyQt应用...")
    try:
        # 添加当前目录到Python路径
        sys.path.insert(0, current_dir)
        
        # 导入并运行PyQt应用
        from pyqt_app import MainWindow
        from PyQt5.QtWidgets import QApplication
        
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        
        print("✓ PyQt应用启动成功")
        print("\n应用已启动，请查看桌面窗口")
        
        sys.exit(app.exec_())
        
    except Exception as e:
        print(f"✗ 启动PyQt应用失败: {e}")
        import traceback
        traceback.print_exc()
        input("按回车键退出...")

if __name__ == "__main__":
    main()